import 'dart:async';

import 'package:flutter_app/bean/problem_report_type_entity.dart';
import 'package:flutter_app/network/Api.dart';
import 'package:flutter_app/network/ResultData.dart';
import 'package:flutter_app/utils/EventBusUtils.dart';
import 'package:flutter_app/utils/toast_utils.dart';
import 'package:get/get.dart';

import 'query_detail/query_detail_view.dart';
import 'query_list_state.dart';

class QueryListLogic extends GetxController {
  final QueryListState state = QueryListState();

  late String groupId; // 小组ID
  late String orgId; // 单位ID
  late String memberStatus; //成员自身的状态

  late StreamSubscription<CollectAddNum> collectAddNum;

  late bool addNum = false; // 是否需要刷新数据，问题详情页面修改了数据就需要，没有修改就不需要

  @override
  void onInit() {
    super.onInit();

    groupId = Get.arguments["groupId"];
    orgId = Get.arguments["orgId"];
    memberStatus = Get.arguments["memberStatus"];
  }

  @override
  void onReady() {
    super.onReady();
    listProblemReportType();
    // 监听bus
    collectAddNum = bus.listen((event) => addNum = true);
  }

  /// 获取问题清单类型列表[2.0]
  Future<void> listProblemReportType() async {
    Map<String, dynamic> param = {
      "groupId": groupId,
      "orgId": orgId,
    };
    ResultData resultData = await Api.listProblemReportType(param);
    if (resultData.isSuccess) {
      state.problemReportTypeEntity = ProblemReportTypeEntity.fromJson(resultData.data['data']);
      update();
    } else {
      toast.show(resultData.data["message"]);
    }
  }

  // item 跳转到 问题详情
  void goToQueryDetailPage(String? name, String? code) {
    // 跳转页面时，先把标记设置为false
    addNum = false;
    Get.to(() => QueryDetailPage(title: "问题详情",), arguments: {
      "typeName": name ?? "",
      "problemCode": code ?? "",
    }
    )?.then((value) {
      if (addNum) {
        listProblemReportType();
      }
    });
  }


  @override
  void onClose() {
    super.onClose();
    collectAddNum.cancel();
  }
}
